package com.hwq.sql.script.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hwq.sql.script.entity.User;
import com.hwq.sql.script.exception.ClientException;
import com.hwq.sql.script.model.po.UserPO;
import com.hwq.sql.script.model.vo.ResultVO;
import com.hwq.sql.script.model.vo.UserVO;
import com.hwq.sql.script.service.UserService;
import com.hwq.sql.script.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("user/save")
    public ResultVO<Object> save(@RequestBody User user) {
        try {
            userService.save(user);
            return HttpUtil.success("新增成功");
        } catch (DuplicateKeyException ex) {
            return HttpUtil.failure("名称或者账号已存在");
        }
    }

    @PostMapping("user/updateById")
    public ResultVO<Object> updateById(@RequestBody User user) {
        userService.updateById(user);
        return HttpUtil.success("修改成功");
    }

    @PostMapping("user/removeById")
    public ResultVO<Object> removeById(@RequestBody UserPO po) {
        userService.removeById(po.getId());
        return HttpUtil.success("删除成功");
    }

    @PostMapping("user/validateName")
    public ResultVO<Object> validateName(@RequestBody UserPO po) {
        User user = userService.getByName(po.getName());
        ClientException.judge(user != null, "名称已存在");
        return HttpUtil.success("可用名称");
    }

    @PostMapping("user/validateAccount")
    public ResultVO<Object> validateAccount(@RequestBody UserPO po) {
        User user = userService.getByAccount(po.getAccount());
        ClientException.judge(user != null, "账号已存在");
        return HttpUtil.success("可用账号");
    }

    @PostMapping("user/page")
    public ResultVO<IPage<UserVO>> page(@RequestBody UserPO po) {
        IPage<UserVO> page = userService.page(po);
        return HttpUtil.success("查询成功", page);
    }

}
